"""
数据库相关的操作：增删改查
"""
from apps.model.models import NewUser, Project
from fastapi.exceptions import HTTPException
from sqlalchemy.orm import Session
from apps.model.schames import LoginUserIn
from apps.model import schames
from sqlalchemy import or_, desc


def paginate_by_page_size(objs, page=1, size=None):
    """分页查询"""
    if (page if page else 0) > 0 and (size if size else 0) > 0:
        offset_data = (page - 1) * (size if size else 0)
        objs = objs.offset(offset_data).limit(size)
    return objs


def create_register_user(db: Session, body):
    """创建用户"""
    # sql 表的实例
    user_obj = NewUser(**body.dict())
    # 加密
    user_obj.hash_password(user_obj.password)
    try:
        db.add(user_obj)
        db.commit()  # 提交
    except Exception as msg:
        # log 日志 输出 msg
        raise HTTPException(400, detail='用户名已存在')


def login_verify_user(db: Session, body: LoginUserIn):
    """登录 - 校验用户名 和 密码"""
    # 查询数据库账号，校验密码
    user_obj = db.query(NewUser).filter_by(username=body.username)
    # 判断有没有查询结构
    if user_obj.count() > 0:
        # 有账号 -- 校验密码
        obj = user_obj.first()
        print(obj)
        res = obj.verify_password(body.password)
        if res:
            print("1111111111111")
            return obj
        else:
            print("2222222222")
            raise HTTPException(400, detail='用户名或密码不正确')
    else:
        raise HTTPException(400, detail='用户名或密码不正确')


def create_project(db: Session, body, user_id):
    project_obj = Project(user_id=user_id, **body.dict())
    # 判断项目名称有没重复，
    if db.query(Project).filter_by(project_name=body.project_name).count():
        # 项目名称重复添加
        raise HTTPException(status_code=400, detail=f"项目名称：{body.project_name}已存在")
    # 入库
    try:
        db.add(project_obj)
        db.commit()  # 提交
        db.flush(project_obj)   # 多了一个id
    except Exception as msg:
        # log 日志 输出 msg
        print(msg)
        raise HTTPException(400, detail='创建项目失败')
    return project_obj


def query_project_by_id(db: Session, _id: int):
    """根据项目id查询"""
    project_obj = db.query(Project).filter_by(id=_id)
    if project_obj.count() > 0:
        # 查询到数据
        return project_obj.first()
    else:
        raise HTTPException(400, detail='项目id不存在')


def is_project_by_id_exists(db: Session, _id: int):
    """判断项目id是否存在"""
    project_obj = db.query(Project).filter_by(id=_id)
    if project_obj.count() > 0:
        return project_obj
    else:
        raise HTTPException(400, detail='项目id不存在')


def update_project(db: Session, _id: int, body: schames.ProjectUpdateIn):
    """跟新 项目 根据id"""
    # 先判断，有没有项目id
    project_obj = is_project_by_id_exists(db, _id)
    try:
        # 更新
        project_obj.update(body.dict(exclude_unset=True))
        db.commit()
        db.flush(project_obj)   # 刷新更新后的对象
    except Exception as msg:
        # log 日志 输出 msg
        print(msg)
        raise HTTPException(400, detail='更新项目失败')
    return project_obj.first()


def delete_project(db: Session, _id: int):
    project_obj = is_project_by_id_exists(db, _id)
    try:
        # 更新
        project_obj.delete()
        db.commit()
    except Exception as msg:
        # log 日志 输出 msg
        print(msg)
        raise HTTPException(400, detail='删除项目失败')


def query_all_project(db: Session, page=1, size=None, project_name=''):
    """查询全部"""
    # 1.全部
    objs = db.query(Project)
    # 2.排序--desc 倒叙
    objs = objs.order_by(desc(Project.id))
    # 3.根据条件查询
    print(f"条件查询：project_name--{project_name}")
    objs = objs.filter(
        or_(Project.project_name.contains(project_name), project_name == ''),
    )
    # 4.分页
    objs = paginate_by_page_size(objs, page, size)
    return objs.all()




